package com.designpatterns;

import java.util.LinkedList;
import java.util.Queue;

public class ProducerConsumerProblem {
	
	private Queue<String> messages = new LinkedList<String>();
	
	public String getMessage(){
		
		synchronized (messages) {
			try {
				while(messages.isEmpty()){
					System.out.println("**********************Queue started waiting*************************");
					messages.wait();
					System.out.println("**********************Queue finished waiting*************************");
				}
			} catch (InterruptedException e) {
				throw new RuntimeException(e);
			}
		}
		return messages.poll();
	}
	
	public void add(String message){
		synchronized (messages) {
			messages.add(message);
			messages.notify();
		}
		
	}
	
	public static void main(String[] args) {
		final ProducerConsumerProblem problem = new ProducerConsumerProblem();
		System.out.println("Creating First Thread");
		new Thread(new Runnable(){
			@Override
			public void run() {
				System.out.println("****************First Thread Running**************");
				System.out.println("Got Message From Queue: "+problem.getMessage());
			}
			
		}).start();
		
		
		System.out.println("Creating Second Thread");
		new Thread(new Runnable(){
			@Override
			public void run() {
				System.out.println("****************Second Thread Running**************");
				problem.add("Hello");
			}
			
		}).start();
	}
}
